package books

import java.util.regex.Matcher
import java.util.regex.Pattern

class Book {
	
	String title
	String author
	String description
	String isbn
	String language
	String category
	int minGradeLevel
	int maxGradeLevel
			
    static constraints = {	
		title(blank: false)
		author(blank: false)
		description(maxsize: 1000, widget:"textarea")	
		isbn validator: {
			def pattern
			it = it.replaceAll("-","")
			System.out.println(it)
			if (it.size() == 13){
				pattern = ~/(?=.{13}$)97(?:8|9)\d\d\d\d\d\d\d\d\d\d$/
				if (!pattern.matcher(it).matches())
					return 'isbnValidator.message'
			}
			else if (it.size() == 10){
				pattern = ~/(?=.{10}$)97(?:8|9)\d\d\d\d\d\d\d$/
				if (!pattern.matcher(it).matches())
					return 'isbnValidator.message'
			}
			else
				return 'isbnValidator.message'
		}
		category(blank: false, inList: ['General Leisure Reading', 'Reading Skills', 'Math Skills', 'Health', 'Science'], widget:"list")
		language(blank: true)
		minGradeLevel(range:0..6, widget:"list")
		maxGradeLevel(range:0..6, widget:"list")
	}
	
	@Override
	def beforeInsert() {
		isbn = isbn.replaceAll("-", "")
	}
	
	@Override
	def beforeUpdate() {
		isbn = isbn.replaceAll("-", "")
	}
}
